package com.zzxz.practicaltrainingsys.controller;


import com.zzxz.practicaltrainingsys.entity.Team;
import com.zzxz.practicaltrainingsys.service.MemberService;
import com.zzxz.practicaltrainingsys.service.TeamService;
import com.zzxz.practicaltrainingsys.vo.ViewTeam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "Team")
@RestController
@RequestMapping("/team")
@CrossOrigin
public class TeamController {

    @Autowired
    private TeamService  TeamService;
    @Autowired
    private TeamService teamService;

    //在组队信息表（team）里插入组长学号、组名、选题编号、邀请码、项目编号、小组组号。
    // http://127.0.0.1:8080/team/insertTeam?leader_id=1&team_name=1&topic_id=1&invite_code=1&project_id=1&group_id=1
    @PostMapping("/insertTeam")
    public int insertTeam(@RequestBody Team team){
        return TeamService.insertTeam(team);
    }

    //插入副组长，根据组号更新team表中的viceleader_id（副组长）字段
    // http://127.0.0.1:8080/team/updateViceleaderId?viceleader_id=1&group_id=1
    @PutMapping("/updateViceleaderId")
    public int updateViceleaderId(@RequestBody Team team){
        return TeamService.updateViceleaderId(team);
    }

    //在组队信息表（team）根据组长学号查取邀请码。
    // http://127.0.0.1:8080/team/getInviteCodeByLeaderId?leader_id=1
    @GetMapping("/getInviteCodeByLeaderId")
    public String getInviteCodeByLeaderId(@RequestParam("leader_id") Integer leader_id){
        return TeamService.getInviteCodeByLeaderId(leader_id);
    }

    //在组队信息表（team）根据小组组号更新小组成绩。
    // http://127.0.0.1:8080/team/updateGroupMarks?group_marks=1&group_id=1
    @PutMapping("/updateGroupMarks")
    public int updateGroupMarks(@RequestBody Team team){
        return TeamService.updateGroupMarks(team);
    }

    //根据组号在组队信息表（team）查询小组成绩
    // http://127.0.0.1:8080/team/getGroupMarksByGroupId?group_id=1
    @GetMapping("/getGroupMarksByTeamId")
    public String getGroupMarksByTeamId(@RequestParam("team_id") Integer team_id){
        return TeamService.getGroupMarksByTeamId(team_id);
    }

    //查找所有的组队信息
    // http://127.0.0.1:8080/team/getAllTeams
    @GetMapping("/getAllTeams")
    public Map<String, Object> getAllTeams(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        int offset = (pageNum - 1) * pageSize;
        List<ViewTeam> list = TeamService.getViewTeamsPage(offset, pageSize);
        int total = TeamService.getTotalCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);

        return result;
    }

    @ApiOperation("根据选题ID统计该选题下的小队数量")
    @GetMapping("/countByTopicId")
    public int countByTopicId(@RequestParam("topic_id") Integer topic_id) {
        return TeamService.countByTopicId(topic_id);
    }

    @Autowired
    private MemberService memberService;

    @ApiOperation("创建队伍并自动加入组长为成员")
    @PostMapping("/createTeamAndJoin")
    public Map<String, Object> createTeamAndJoin(@RequestBody Team team) {
        Map<String, Object> params = new HashMap<>();
        params.put("leader_id", team.getLeader_id());
        params.put("team_name", team.getTeam_name());
        params.put("topic_id", team.getTopic_id());
        params.put("invite_code", team.getInvite_code());
        params.put("project_id", team.getProject_id());

        return TeamService.createTeamAndJoin(params, memberService);
    }

    @ApiOperation("根据邀请码查找小队信息")
    @GetMapping("/findByInviteCode")
    public Team findByInviteCode(@RequestParam String invite_code) {
        return TeamService.findByInviteCode(invite_code);
    }

    @ApiOperation("根据项目ID和选题ID统计该选题下的小队数量")
    @GetMapping("/countByProjectAndTopic")
    public int countByProjectAndTopic(@RequestParam("project_id") Integer project_id,
                                      @RequestParam("topic_id") Integer topic_id) {
        return teamService.countByProjectAndTopic(project_id, topic_id);
    }

    //判断角色
    @GetMapping("/role")
    public String getUserRole(@RequestParam Integer studentId){
        return teamService.getUserRole(studentId);
    }

    @ApiOperation("根据team_id获取小队信息")
    @GetMapping("/getTeamInfo")
    public Team getTeamInfo(@RequestParam("team_id") Integer team_id) {
        return teamService.getTeamInfo(team_id);
    }
    //根据学号和项目id查找邀请码
    @GetMapping("/invite-code")
    public ResponseEntity<?> getTeamInviteCode(@RequestParam Integer studentId,
                                               @RequestParam Integer projectId) {
        try {
            ViewTeam team = teamService.getTeamByStudentAndProject(studentId, projectId);

            // 构建返回结果，只返回需要的字段
            TeamInviteCodeResponse response = new TeamInviteCodeResponse();
            response.setInviteCode(team.getInvite_code());
            response.setTeamName(team.getTeam_name());
            response.setProjectName(team.getProject_name());

            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("参数错误: " + e.getMessage());
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器内部错误");
        }
    }

    /**
     * RESTful风格的API - 通过路径参数获取
     */
    @GetMapping("/student/{studentId}/project/{projectId}/invite-code")
    public ResponseEntity<?> getTeamInviteCodeRestful(@PathVariable Integer studentId,
                                                      @PathVariable Integer projectId) {
        return getTeamInviteCode(studentId, projectId);
    }

    // 内部响应类
    @Getter
    public static class TeamInviteCodeResponse {
        // Getters and Setters
        private String inviteCode;
        private String teamName;
        private String projectName;

        public void setInviteCode(String inviteCode) {
            this.inviteCode = inviteCode;
        }

        public void setTeamName(String teamName) {
            this.teamName = teamName;
        }

        public void setProjectName(String projectName) {
            this.projectName = projectName;
        }
    }
    @ApiOperation("根据选题ID查询团队列表")
    @GetMapping("/topic/{topic_id}")
    public List<Team> getTeamsByTopicId(@PathVariable Integer topic_id) {
        return teamService.getTeamsByTopicId(topic_id);
    }

    @ApiOperation("更新团队成绩")
    @PostMapping("/updateScore")
    public Map<String, Object> updateTeamScore(@RequestBody Map<String, Object> params) {
        Integer team_id = (Integer) params.get("team_id");
        Double group_marks = Double.valueOf(params.get("group_marks").toString());

        int result = teamService.updateTeamScore(team_id, group_marks);

        Map<String, Object> response = new HashMap<>();
        response.put("success", result > 0);
        response.put("message", result > 0 ? "更新成功" : "更新失败");

        return response;
    }

}

